#!/usr/bin/env python
# -*- coding: utf-8 -*-
import mysql.connector
from mysql.connector import pooling


def sync_user_data():
    # 源数据库配置 (sysmandb)
    src_db = {
        # 'host': '10.1.213.159',
        # 'user': 'GTXS_user',
        # 'password': 'GTXS_user_JG123',
        'host': '10.99.81.155',
        'port': 8306,
        'user': 'root',
        'password': 'Lgmi6395',
        'database': 'jg_main'
    }

    # '''目标数据库配置 (jg_usercenter)'''
    dest_db = {
        'host': '10.99.81.155',
        'port': 8306,
        'user': 'jg_usercenter',
        'password': 'Jg_usercenter_20250312',
        'database': 'jg_usercenter'
    }

    try:
        # 创建数据库连接
        # src_conn = mysql.connector.connect(**src_db)
        src_connection_pool = pooling.MySQLConnectionPool(
            pool_name="srcpool",
            pool_size=5,
            pool_reset_session=True,
            **src_db
        )
        src_conn = src_connection_pool.get_connection()

        # dest_conn = mysql.connector.connect(**dest_db)
        dest_connection_pool = pooling.MySQLConnectionPool(
            pool_name="destpool",
            pool_size=5,
            pool_reset_session=True,
            **dest_db
        )
        dest_conn = dest_connection_pool.get_connection()

        src_cursor = src_conn.cursor(dictionary=True)
        dest_cursor = dest_conn.cursor()

        # 1. 查询源数据,注意数据范围
        src_cursor.execute("""
            select id,
                   tenant_id,
                   user_name, -- user_name
                   user_nickname, -- real_name
                   user_email, -- email
                   user_password, -- password
                   department, --
                   user_tel, -- phone
                   IF(user_type = 'DRIVER', 'person', 'corp') user_type, -- user_type (driver)
                   IF(user_type = 'DRIVER', 'driver', null) driver_user_type,
                   credit_id, -- id_card
                   user_birthday, -- birthday
                   user_wechat, --
                   user_avatar, -- avatar
                   deleted_tag, -- deleted_tag
                   create_date, -- create_date
                   create_user, -- create_user
                   change_date, --  change_date
                   change_user, -- change_user
                   user_code
            from sys_user where 1=1  and user_name <> 'admin'
        """)

        # 2. 准备插入语句（根据实际表结构调整字段）
        insert_query = """
            INSERT INTO sys_user (
                id, tenant_id, user_name, real_name, password, state, avatar, birthday, 
                email, phone, deleted_tag, create_user, create_date, change_user, change_date,
                id_card, remark, user_type, driver_user_type, corp_code, user_code
            ) VALUES (
                %(id)s, %(tenant_id)s, %(user_name)s, %(user_nickname)s, %(user_password)s, '1', %(user_avatar)s, %(user_birthday)s,
                %(user_email)s, %(user_tel)s, %(deleted_tag)s, %(create_user)s, %(create_date)s, %(change_user)s, %(change_date)s,
                %(credit_id)s, 'sync from ymt', %(user_type)s, %(driver_user_type)s, '1012', %(user_code)s
            )
        """

        # 3. 执行同步
        batch_size = 1000
        count = 0

        for user in src_cursor:
            processed_user = dict(user)  # 创建原始数据的副本
            # 使用Python函数处理特定字段
            # processed_user['user_code'] = genCode('U')

            # 执行插入
            dest_cursor.execute(insert_query, processed_user)
            count += 1

            # 分批提交
            if count % batch_size == 0:
                dest_conn.commit()
                print(f"已同步 {count} 条记录")

        dest_conn.commit()  # 提交剩余记录
        print(f"同步完成！总计: {count} 条记录")

    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        dest_conn.rollback()
    finally:
        # 关闭连接
        if src_cursor: src_cursor.close()
        if dest_cursor: dest_cursor.close()
        if src_conn: src_conn.close()
        if dest_conn: dest_conn.close()


if __name__ == "__main__":
    sync_user_data()